import { View, Map, Image, Picker } from "@tarojs/components";
import { useState } from "react";
import Taro, { useRouter, useDidShow } from "@tarojs/taro";
import { getProjectInfoApi } from "../../../utils/api";
import { btq, qtb, formatTime2 } from "../../../utils/to";
import "./index.scss";

import { AtList, AtListItem, AtForm, AtInput, AtButton } from "taro-ui";

import {
  getProjectChangeApi,
  getProjectAdjustApi,
  getAreaApi
} from "../../../utils/api";

import { useSelector, useDispatch } from "react-redux";

const ProjectChange = () => {
  const satellite = useSelector(state => state.yq.satellite);
  const dispatch = useDispatch();
  const router = useRouter();

  // 工程信息数据
  const [detailInfo, setDetailInfo] = useState({});
  const [lng, set_lng] = useState("");
  const [lat, set_lat] = useState("");
  const [lng_center, set_lng_center] = useState("");
  const [lat_center, set_lat_center] = useState("");

  const [size, set_size] = useState(16);

  useDidShow(() => {
    getInfo();
  });

  // 获取详情
  const getInfo = async () => {
    const res = await getProjectInfoApi({
      project_id: router.params.id
    });
    if (res.res === 0) {
      const obj = {
        ...res.record,
        build_timestamp: formatTime2(res.record.build_timestamp * 1000)
      };
      setDetailInfo(obj);
      if (res.record.longitude === 0) {
        set_size(10);
        getAreaApi({
          code: Taro.getStorageSync("code")
        }).then(res => {
          if (res.res === 0) {
            const arr = btq(+res.record.lng, +res.record.lat);
            // set_lng(+arr[0]);
            set_lng_center(+arr[0]);
            // set_lat(+arr[1]);
            set_lat_center(+arr[1]);
          }
        });
      } else {
        set_lng(
          +btq(res.record.longitude / 1000000, res.record.latitude / 1000000)[0]
        );
        set_lng_center(
          +btq(res.record.longitude / 1000000, res.record.latitude / 1000000)[0]
        );
        set_lat(
          +btq(res.record.longitude / 1000000, res.record.latitude / 1000000)[1]
        );
        set_lat_center(
          +btq(res.record.longitude / 1000000, res.record.latitude / 1000000)[1]
        );
      }
    } else {
      Taro.atMessage({
        message: res.msg,
        type: "warning"
      });
    }
  };

  const mapClick = e => {
    set_lng(e.detail.longitude);
    set_lat(e.detail.latitude);
  };

  const fn = () => {
    set_lng(lng => lng - 0.00001);
  };

  const fn2 = () => {
    set_lng(lng => lng + 0.00001);
  };

  const fn3 = () => {
    set_lat(lat => lat + 0.00001);
  };

  const fn4 = () => {
    set_lat(lat => lat - 0.00001);
  };

  const handleChange = (k, v) => {
    setDetailInfo(detailInfo => {
      return {
        ...detailInfo,
        [k]: v
      };
    });
  };

  const onDateChange = () => {};

  const onSubmit = async () => {
    const res = await getProjectChangeApi({
      ...detailInfo,
      project_id: detailInfo.project_id,
      build_timestamp: detailInfo.build_timestamp
        ? Date.parse(new Date(detailInfo.build_timestamp)) / 1000
        : Math.ceil(new Date().getTime() / 1000)
    });
    if (res.res === 0) {
      const arr = qtb(lng, lat);
      const res2 = await getProjectAdjustApi({
        project_id: detailInfo.project_id,
        longitude: arr[0],
        latitude: arr[1]
      });
      if (res2.res === 0) {
        Taro.atMessage({
          message: "修改成功",
          type: "success"
        });
        Taro.navigateBack({
          delta: 1
        });
      } else {
        Taro.atMessage({
          message: res.msg,
          type: "warning"
        });
      }
    } else {
      Taro.atMessage({
        message: res.msg,
        type: "warning"
      });
    }
  };

  const changeSatellite = e => {
    dispatch({ type: "changeSatellite" });
  };

  return (
    <View className="index">
      <View className="mapwrap">
        <Map
          longitude={lng_center}
          latitude={lat_center}
          style={{ width: "100%", height: 300 }}
          scale={size}
          markers={
            lng
              ? [
                  {
                    longitude: lng,
                    latitude: lat,
                    id: new Date().getTime()
                  }
                ]
              : []
          }
          showScale={true}
          onTap={mapClick}
          enable-satellite={satellite}
        ></Map>
        {lng && (
          <>
            <View className="controls item1" onClick={fn}>
              <Image
                src={require("../../../assets/images/left.png")}
                style="width: 40px;height: 40px;"
              />
            </View>
            <View className="controls item2" onClick={fn2}>
              <Image
                src={require("../../../assets/images/right.png")}
                style="width: 40px;height: 40px;"
              />
            </View>
            <View className="controls item3" onClick={fn3}>
              <Image
                src={require("../../../assets/images/top.png")}
                style="width: 40px;height: 40px;"
              />
            </View>
            <View className="controls item4" onClick={fn4}>
              <Image
                src={require("../../../assets/images/bottom.png")}
                style="width: 40px;height: 40px;"
              />
            </View>
          </>
        )}
      </View>

      <View className="button-wrap">
        <View className="button-item" onClick={changeSatellite}>
          {satellite ? "切换标准地图" : "切换卫星地图"}
        </View>
      </View>

      <AtForm>
        <AtInput
          required
          name="name"
          title="工程名称"
          type="text"
          value={detailInfo.name}
          onChange={v => handleChange("name", v)}
        />
        <AtInput
          name="comment"
          title="工程描述"
          type="text"
          value={detailInfo.comment}
          onChange={v => handleChange("comment", v)}
        />
        <AtInput
          name="address"
          title="工程地址"
          type="text"
          placeholder="请输入工程地址"
          value={detailInfo.address}
          onChange={v => handleChange("address", v)}
        />

        <AtInput
          name="building_area"
          title="建筑面积"
          type="text"
          placeholder="请输入建筑面积"
          value={detailInfo.building_area}
          onChange={v => handleChange("building_area", v)}
        />

        <AtInput
          name="building_number"
          title="幢数"
          type="text"
          placeholder="请输入幢数"
          value={detailInfo.building_number}
          onChange={v => handleChange("building_number", v)}
        />

        <AtInput
          name="constructor"
          title="建设单位"
          type="text"
          placeholder="请输入建设单位"
          value={detailInfo.constructor}
          onChange={v => handleChange("constructor", v)}
        />

        <AtInput
          name="constructor_user"
          title="建设单位联系人"
          type="text"
          placeholder="请输入建设单位联系人"
          value={detailInfo.constructor_user}
          onChange={v => handleChange("constructor_user", v)}
        />

        <AtInput
          name="constructor_phone"
          title="建设单位电话"
          type="text"
          placeholder="请输入建设单位电话"
          value={detailInfo.constructor_phone}
          onChange={v => handleChange("constructor_phone", v)}
        />

        <AtInput
          name="builder"
          title="施工单位"
          type="text"
          placeholder="请输入施工单位"
          value={detailInfo.builder}
          onChange={v => handleChange("builder", v)}
        />

        <AtInput
          name="builder_user"
          title="施工单位联系人"
          type="text"
          placeholder="请输入施工单位联系人"
          value={detailInfo.builder_user}
          onChange={v => handleChange("builder_user", v)}
        />

        <AtInput
          name="builder_phone"
          title="施工单位电话"
          type="text"
          placeholder="请输入施工单位电话"
          value={detailInfo.builder_phone}
          onChange={v => handleChange("builder_phone", v)}
        />

        <Picker mode="date" onChange={onDateChange}>
          <AtList>
            <AtListItem
              extraText={detailInfo.build_timestamp}
              title="请选择开工日期"
            ></AtListItem>
          </AtList>
        </Picker>
        <AtButton type="primary" onClick={onSubmit}>
          提交
        </AtButton>
      </AtForm>
    </View>
  );
};

export default ProjectChange;
